/**
 * Created by shandianhaizan on 16/7/1.
 */


define([], function () {

    function _controller($scope, $routeParams, $location, $timeout, httpService) {


        var model ="PointRule";


        $scope.showLoading();




        $scope.addRule = function(){
            $scope.models = $scope.models || [];
            $scope.models.push({});
        };


        $scope.validation = function(editRule){
            if(editRule.leftNum && editRule.rightNum && editRule.rightNum < editRule.leftNum) {
                return {success:false, msg:"右边数字不能小于左边数字"};
            }
            var index = $.inArray(editRule, $scope.models);
            var left = $scope.models[index-1];
            if(left){
                if(!editRule.leftNum || editRule.leftNum < left.rightNum){
                    return {success:false, msg:"左边数字不得小于"+left.rightNum};
                }
            }
            var right = $scope.models[index+1];
            if(right){
                if(!editRule.rightNum || editRule.rightNum> right.leftNum){
                    return {success:false, msg:"右边数字不得大于"+right.leftNum};
                }
            }

            return {success:true};
        };

        $scope.save = function (editRule) {
            var validation = $scope.validation(editRule);
            if(!validation.success) return $scope.msg.show(validation.msg);
            httpService.save(model, editRule).then(function (data) {
                $scope.msg.show(data);
                $scope.getAll();
            });
        };


        $scope.getAll = function () {
            httpService.get(model, {all:true, sort:"createdAt"}).then(function (data) {
                $scope.models = data.data.data;
                $scope.hideLoading();
            });
        };

        $scope.showRemove = function(m){
            $scope.deleteName = m.name;
            $scope.deleteObject = m;
        };



        $scope.remove = function(m){
            httpService.del(model, m.objectId).then(function (data) {
                httpService.removeParent(model, m.objectId).then(function (data) {
                    $scope.msg.show(data);
                    if($scope.isHandleSuccess(data)){
                        $scope.getAll();
                    }
                });
            });
        };



        $scope.getAll();

    }

    return _controller;
});

